package com.zhonghui.license;

import org.apache.logging.log4j.LogManager;
import java.net.SocketException;
import java.util.Enumeration;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.net.InetAddress;
import java.util.List;
import org.apache.logging.log4j.Logger;

public abstract class AbstractServerInfos
{
    private static Logger logger;
    
    public LicenseCheckModel getServerInfos() {
        final LicenseCheckModel result = new LicenseCheckModel();
        try {
            result.setCpuSerial(this.getCPUSerial());
            result.setMainBoardSerial(this.getMainBoardSerial());
        }
        catch (Exception e) {
            AbstractServerInfos.logger.error("获取服务器硬件信息失败", (Throwable)e);
        }
        return result;
    }
    
    protected abstract List<String> getIpAddress() throws Exception;
    
    protected abstract List<String> getMacAddress() throws Exception;
    
    protected abstract String getCPUSerial() throws Exception;
    
    protected abstract String getMainBoardSerial() throws Exception;
    
    protected List<InetAddress> getLocalAllInetAddress() throws Exception {
        final List<InetAddress> result = new ArrayList<InetAddress>(4);
        final Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement();
            final Enumeration inetAddresses = iface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                final InetAddress inetAddr = (InetAddress) inetAddresses.nextElement();
                if (!inetAddr.isLoopbackAddress() && !inetAddr.isLinkLocalAddress() && !inetAddr.isMulticastAddress()) {
                    result.add(inetAddr);
                }
            }
        }
        return result;
    }
    
    protected String getMacByInetAddress(final InetAddress inetAddr) {
        try {
            final byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress();
            final StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < mac.length; ++i) {
                if (i != 0) {
                    stringBuffer.append("-");
                }
                final String temp = Integer.toHexString(mac[i] & 0xFF);
                if (temp.length() == 1) {
                    stringBuffer.append("0" + temp);
                }
                else {
                    stringBuffer.append(temp);
                }
            }
            return stringBuffer.toString().toUpperCase();
        }
        catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    static {
        AbstractServerInfos.logger = LogManager.getLogger((Class)AbstractServerInfos.class);
    }
}
